#!/usr/bin/env python
# _*_ coding:utf-8 _*_
#
# Copyright(c) http://m.ecpark.cn/
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import argparse
import sys
import os

import logging

basedir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, basedir)

log = logging.getLogger(__name__)

formatter = logging.basicConfig(filename="{}/{}".format(basedir, 'transfer.log'),
                                level=logging.INFO,
                                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                                datefmt='%a, %d %b %Y %H:%M:%S')
logging.getLogger("pika").propagate = False

from file_transfer import backup_file_transfer_entry
from ot_utils import get_file_backup_info


def main():
    parser = argparse.ArgumentParser(
        description='mysql backup command line .', usage=None, add_help=True)

    parser.add_argument('--mysql_host', type=str,
                        help='数据库主机IP', required=False)
    parser.add_argument('--mysql_port', '-p', type=int,
                        help='数据库实例端口', required=False)
    parser.add_argument('--rsync_user', '-u', type=str,
                        help='rsync用户', default='dba_rsync', required=False)
    parser.add_argument('--remote_rsync_port', '-r',
                        help='rsync端口', type=int, default=22002, required=False)
    parser.add_argument('--backup_dir', '-d', type=str,
                        help='mysql备份目录', required=False)
    parser.add_argument('--remote_rsync_module', '-m', type=str,
                        help='rsync模块', default='data', required=False)
    parser.add_argument('--remote_host', '-e', type=str,
                        help='远程传输主机', required=False)
    parser.add_argument('--backup_file_name', '-f',
                        type=str, help='备份文件', required=False)
    parser.add_argument('--extra_args', '-t',
                        type=str, help="传输消息类型", required=False)

    parser.add_argument('--version', '-v', action='version',
                        version='version 1.0', help='输出脚本版本信息并退出')

    args = parser.parse_args()

    mysql_host = args.mysql_host
    mysql_port = args.mysql_port
    if mysql_host is not None and mysql_port is not None:
        mysql_host = args.mysql_host
        mysql_port = args.mysql_port
        rsync_user = args.rsync_user
        remote_rsync_port = args.remote_rsync_port
        remote_rsync_module = args.remote_rsync_module
        remote_host = args.remote_host
        backup_file_name = args.backup_file_name
        backup_dir = args.backup_dir
        extra_args = args.extra_args
    else:
        try:
            log.info(
                'Argument not pass from the command line and we will get argument from the config file. ')
            config_option = __import__('info_config')
            mysql_host = config_option.mysql_host
            mysql_port = config_option.mysql_port
            rsync_user = config_option.rsync_user
            remote_rsync_port = config_option.remote_rsync_port
            remote_rsync_module = config_option.remote_rsync_module
            key_max = config_option.transfer_concurrency
            remote_host = config_option.remote_host
            extra_args = config_option.extra_args
            # backup_file_name = config_option.backup_file_name
            # backup_dir = config_option.backup_dir
        except ImportError as e:
            log.exception("Can not load config file options , and now exit")
            return 1
        last_backup_ok_file_info = get_file_backup_info(
            mysql_host=mysql_host, mysql_port=mysql_port)
        try:
            backup_file_name = last_backup_ok_file_info.get('backup_file_name')
            backup_dir = last_backup_ok_file_info.get('backup_dir')
        except AttributeError as e:
            log.exception(str(e))
            # raise e
            backup_file_name = config_option.backup_file_name
            backup_dir = config_option.backup_dir
        backup_file_transfer_entry(backup_dir=backup_dir,
                                   backup_file_name=backup_file_name,
                                   remote_host=remote_host,
                                   remote_rsync_module=remote_rsync_module,
                                   remote_rsync_port=remote_rsync_port,
                                   rsync_user=rsync_user,
                                   mysql_host=mysql_host,
                                   mysql_port=mysql_port,
                                   extra_args=extra_args,
                                   key_max=key_max)


if __name__ == "__main__":
    sys.exit(main())
